import React from 'react'
import { forwardRef, useState, memo } from 'react';
import { CartOptionStyle, GoodsOptionStyle } from './style';
import { useEffect } from 'react';
import { Toast } from 'antd-mobile';

// import { useDispatch, useSelector } from 'react-redux'
// import { updateSubmitConfig } from '@store/actionCreators'

const cartNumConfig = {
  action: 'caigou',
  id: '',
  uniacid: ''
}

const cartType = [
  { value: '常规车', key: 'cgc001' },
  { value: '冷链车', key: 'llc002' },
]

const cartLength = [
  { value: '4.2米', key: 'len003' },
  { value: '6.8米', key: 'len002' },
  { value: '9.6米', key: 'len001' }

]


export const GoodsItem = memo((props) => {

  const { goods } = props

  return (
    <div className="goods flex-row">
      <div className="left">
        <img src={"https://res.lexiangpingou.cn/" + goods.gimg} alt="" />
      </div>
      <div className="right flex-column">
        <p className="title"> {goods.name} </p>
        <div className="sale-num">
          <span>已售{goods.salenum}</span>
          <span>剩余{goods.stock ? goods.stock : 0}</span>
        </div>
        <div className="price">
          ￥{goods.sprice ? goods.sprice : '0.00'}
        </div>
      </div>
    </div>
  )
})

const CartTypeOption = (props, cartOption_ref) => {

  const [cartTypeIndex, setCartTypeIndex] = useState(-1)
  const [cartLengthIndex, setCartLengthIndex] = useState(-1)
  const { uniacid, gid } = props
  cartNumConfig.uniacid = uniacid
  cartNumConfig.id = gid
  useEffect(() => {


    console.log(cartLengthIndex, cartTypeIndex, "应该在这里将 发送 ref 的数据")


  }, [cartLengthIndex, cartTypeIndex])


  function handelRefData() {
    let object = {}
    if (cartTypeIndex !== -1 && cartLengthIndex !== -1) {
      object.cartSize = cartLength[cartLengthIndex].value
      object.cartType = cartType[cartTypeIndex].value
    }
    return JSON.stringify(object)
  }

  return (
    < CartOptionStyle >
      {/* 车辆属性 */}

      <div className="cart-option flex-column" style={{ padding: '.4rem 0' }}>

        <input type="hidden" name="" value={handelRefData()} ref={cartOption_ref} />

        <div className="option-items" >
          <p className="option-text">车辆属性</p>
          <ul className=" flex-row">
            {
              cartType.map((val, key) => {
                return (
                  <li key={key + val.key} onClick={e => { setCartTypeIndex(key) }} className={key === cartTypeIndex ? 'active' : ''}>{val.value}</li>
                )
              })
            }
          </ul>
          <ul className=" flex-row">
            {
              cartLength.map((val, kex) => {
                return (
                  <li key={kex + val.key} onClick={e => { setCartLengthIndex(kex) }} className={kex === cartLengthIndex ? 'active' : ''}>{val.value}</li>
                )
              })
            }
          </ul>
        </div>
      </div>

    </CartOptionStyle >
  )

}

const GoodsOption = (props, goodsOption_ref) => {

  const [selectedOptionList, setSelectedOptionList] = useState([])  // 选中的规格的数组
  const [concatOption, setConcatOption] = useState('') // 拼接好的选中规格
  const { goodsOption } = props


  useEffect(() => {

    let havePackType = goodsOption.find((item) => { return item.name === '包装类型' })
    if (havePackType) {
      cartNumConfig.packtype = havePackType.option[selectedOptionList?.[0]]
      console.log(cartNumConfig)
    }

    if (selectedOptionList.length === goodsOption.length) {
      props.updateOptionPrice(concatOption)
      console.log('通知goodsItem 更新价格')
    } else {
      console.log('当前有多个规格,只选择了部分规格')
    }

  }, [selectedOptionList, concatOption])


  return (
    <>
      {/* 商品规格 */}
      <input type="hidden" name="" value={JSON.stringify({ specs: concatOption, so_list: selectedOptionList })} ref={goodsOption_ref} />
      <GoodsOptionStyle>
        {
          <div className="goods-option flex-column" style={{ padding: '.4rem 0' }}>
            {

              goodsOption.map((itex, kex) => {
                return (
                  <div key={kex + itex.name} className="option-items" >
                    <p className="option-text">{itex.name}</p>
                    <ul className=" flex-row">
                      {
                        itex.option.map((itey, key) => {
                          return (
                            <li key={key + itey} onClick={e => { saveIndex(kex, key) }} className={key === selectedOptionList[kex] ? 'active' : ''}>{itey}</li>
                          )
                        })
                      }
                    </ul>
                  </div>
                )
              })
            }

          </div>
        }
      </GoodsOptionStyle>
    </>
  )




  function saveIndex(x, y) {
    //  选择规格

    let temp = []
    temp = selectedOptionList
    temp[x] = y
    let str = ''
    goodsOption.map((item, key) => (
      item.option.map((optionItem, optionIndex) => (
        (selectedOptionList[key] === optionIndex) && (str += optionItem + '+')
      )
      )
    ))

    str = str.substr(0, str.length - 1)
    setSelectedOptionList(temp)
    setConcatOption(str)
  }
}

const Counter = (props, counter_ref) => {

  const [goodsNum, setgoodsNum] = useState(1)
  return (
    <>
      <input type="hidden" name="" value={goodsNum} ref={counter_ref} />
      <div className="num flex-row">
        <div className="num-limit">需求数量 {/*<span>{minDetail.min_num}起发</span>*/}  </div>
        <div className="num-input">
          <div className="content flex-row">
            <div className="cube" onClick={e => { changeGoodsNum('reduce') }} > - </div>
            <input className="goodsnum" type="number" name="goodsNum" value={goodsNum} onChange={e => {
              if (e.target.value === "") {
                setgoodsNum('')
              } else {
                setgoodsNum(parseInt(e.target.value))
              }
            }} />
            <div className="cube" onClick={e => { changeGoodsNum('plus') }} > + </div>
          </div>
        </div>
      </div>
    </>
  )

  function changeGoodsNum(type) {
    // 改变购买商品数量
    if (type === 'reduce') {
      if (goodsNum <= 1) {
        Toast.info('不能再减啦', 1)
      } else {
        setgoodsNum(parseInt(goodsNum) - 1)
      }
    } else {
      setgoodsNum(parseInt(goodsNum) + 1)
    }
  }


}

export const ForwardCounter = memo(forwardRef(Counter))
export const ForwardCartTypeOption = memo(forwardRef(CartTypeOption))
export const ForwardGoodsOption = memo(forwardRef(GoodsOption))